package com.jwaoo.chat.session.avchat;

import android.bluetooth.BluetoothDevice;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Build;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.cavan.android.CavanBleDevice;
import com.cavan.android.CavanBleDeviceAdapter;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.log.LogUtil;
import com.jwaoo.chat.ChatHelpter;
import com.jwaoo.chat.R;
import com.jwaoo.chat.ui.WaveView;
/**
 * Created by jwaoo on 2017/11/8.
 */

public class BluetoothView {
    private WindowManager windowManager;
    private View scaning;
    private View bluetooths;
    private ListView listView;
    private View bluetoothView;
    private OnItemSelectedListener listener;
    private WindowManager.LayoutParams layoutParams;
    private final String BAND = "SenseBand";
    private final String VIBE = "Sensevibe";

    private BluetoothHelper bluetoothHelper;
    public BluetoothView(WindowManager windowManager,OnItemSelectedListener listener){
        this.windowManager = windowManager;
        this.listener = listener;
    }

    private void initData(){
        if (bluetoothHelper == null){
            bluetoothHelper = new BluetoothHelper(bluetoothListener);
            bluetoothHelper.setListView(listView);
            bluetoothHelper.initBluetooth();
            bluetoothHelper.initTimer();
        }else {
            bluetoothHelper.setListView(listView);
        }
    }

    public View getBaseView(){
        return bluetoothView;
    }

    private void initView(){
        if (CommonUtils.isEnFloat()){
            layoutParams = new WindowManager.LayoutParams();
            layoutParams.format = PixelFormat.TRANSLUCENT;
            layoutParams = ChatHelpter.getFloatConfig(layoutParams);
            layoutParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// 焦点
            layoutParams.gravity = Gravity.TOP|Gravity.LEFT;
        }

        bluetoothView = View.inflate(ChatHelpter.getContext(), R.layout.avchat_bluetooth,null);
        listView = bluetoothView.findViewById(R.id.listview);
        scaning = bluetoothView.findViewById(R.id.scaning);
        bluetooths = bluetoothView.findViewById(R.id.bluetooths);
        bluetoothView.findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeBluetoothView();
            }
        });

        WaveView waveView = bluetoothView.findViewById(R.id.view_wave);
        waveView.setDuration(5000);
        waveView.setStyle(Paint.Style.FILL);
        waveView.setColor(Color.RED);
        waveView.setInterpolator(new LinearOutSlowInInterpolator());
        waveView.start();
    }

    public void showView(){
        initView();
        initData();
        bluetoothHelper.startSearch();
        if (CommonUtils.isEnFloat()) {
            windowManager.addView(bluetoothView,layoutParams);
        }else {
            SearchBluetoothActivity.startSearchBluetoothActivity();
        }

    }

    private String divName;

    public void doBluetoothOption(int mode,int level,boolean isSpeedByFreq){
        bluetoothHelper.doBluetoothOption(mode,level,isSpeedByFreq);
    }

    private String connectedDivName="";
    private boolean isConnected = false;


    public void onDestoryBluetooth(){
        bluetoothHelper.doBluetoothDisConnect();
        bluetoothHelper.stopTimer();

        closeView();
    }

    private void closeView(){
        try{

            bluetoothHelper.stopScan();
            if (CommonUtils.isEnFloat()) {
                windowManager.removeView(bluetoothView);
            }else {
                SearchBluetoothActivity.closeSearchView();
            }
            bluetoothView = null;
        }catch (Exception ex){
            LogUtil.d(BluetoothView.class.getSimpleName(),ex.toString());
        }

    }

    public void closeBluetoothView(){
        closeView();
    }

    private BluetoothHelper.BluetoothOptionListener bluetoothListener = new BluetoothHelper.BluetoothOptionListener() {
        @Override
        public View getView(final CavanBleDeviceAdapter adapter , final CavanBleDevice device, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(ChatHelpter.getContext())
                    .inflate(R.layout.avchat_blue_item, null);

            View view_item = view.findViewById(R.id.view_item);
            final ImageView imageView = view.findViewById(R.id.img_icon_div);
            final TextView btn_connected = view.findViewById(R.id.btn_connected);
            final ProgressBar progress = view.findViewById(R.id.progress);
            final TextView tv_name = view.findViewById(R.id.tv_name);
            String blueAddress = device.getDevice().getAddress();
            String[] blueAddressSub = blueAddress.split(":");
            String blueAddressNew = null;
            if (blueAddressSub != null && blueAddress.length() >= 2) {
                blueAddressNew = blueAddressSub[blueAddressSub.length - 2]
                        + blueAddressSub[blueAddressSub.length - 1];
            }
            final String name = device.getName() + blueAddressNew;
            int imgSrcId = R.drawable.prop_find_icon_01;
            if (name.contains(BAND)){
                imgSrcId = R.drawable.prop_find_icon_03;
            }else if (name.contains(VIBE)){
                imgSrcId = R.drawable.prop_find_icon_02;
            }
            Bitmap bitmap = BitmapFactory.decodeResource(ChatHelpter.getContext().getResources(),imgSrcId);
            imageView.setImageBitmap(bitmap);
            if (connectedDivName.equals(device.getName())){
                view_item.setBackgroundResource(R.drawable.prop_find_di_p);
                if (isConnected) {
                    btn_connected.setText(ChatHelpter.getContext().getText(R.string.blutooth_disconnect));
                }
                progress.setVisibility(isConnected ? View.GONE : View.VISIBLE);
                btn_connected.setVisibility(isConnected ? View.VISIBLE : View.GONE);
            }
            view_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setBackgroundResource(R.drawable.prop_find_di_p);
                    imageView.setBackgroundResource(R.drawable.prop_find_icon_di_p);
                    int imgSrcId = R.drawable.prop_find_icon_05;
                    if (name.contains(BAND)){
                        imgSrcId = R.drawable.prop_find_icon_04;
                    }else if (name.contains(VIBE)){
                        imgSrcId = R.drawable.prop_find_icon_06;
                    }
                    Bitmap bitmap = BitmapFactory.decodeResource(ChatHelpter.getContext().getResources(),imgSrcId);
                    imageView.setImageBitmap(bitmap);
                    if (Build.VERSION.SDK_INT >= 23){
                        tv_name.setTextColor(ChatHelpter.getContext().getColor(R.color.white));
                    }else {
                        ColorStateList csl = ChatHelpter.getContext().getResources().getColorStateList(R.color.white);
                        if (csl != null) {
                            tv_name.setTextColor(csl);
                        }
                    }
                    BluetoothDevice bluetoothDevice = device.getDevice();
                    divName = device.getName();
                    connectedDivName = divName;
                    if (isConnected) {
                        bluetoothHelper.doBluetoothDisConnect();
                        connectedDivName = "";
                        LogUtil.d("BluetoothView","press disconnected");
                        isConnected = false;
                        listener.onConnected(false,connectedDivName);
                        bluetoothHelper.setCurrentDevice(null);
                    }else {
                        progress.setVisibility(View.VISIBLE);
                        btn_connected.setVisibility(View.GONE);
                        bluetoothHelper.doBluetoothConnect(bluetoothDevice.getAddress());
                        bluetoothHelper.setCurrentDevice(device);
                    }
                    adapter.notifyDataSetChanged();
                }
            });

            tv_name.setText(device.getName() + blueAddressNew);
            return view;
        }

        @Override
        public void onScanResult() {
            scaning.setVisibility(View.GONE);
            bluetooths.setVisibility(View.VISIBLE);
        }


        @Override
        public void onOptionSpeed(int speed) {
            listener.onOptionSpeed(speed);
        }

        @Override
        public void onConnectionStateChanged(boolean connected) {
            listener.onConnected(connected,divName);
            if (!connected) {
                connectedDivName = "";
                LogUtil.d("BluetoothView","disconnected");
                isConnected = false;
            }else {

                connectedDivName = divName;
                isConnected = true;
                closeBluetoothView();
                LogUtil.d("BluetoothView","connected");
                if (!divName.contains(VIBE)) {
                    bluetoothHelper.startTimer();
                }
            }
        }
    };

    public interface OnItemSelectedListener{
        void onConnected(boolean isConnected,String name);
        void onOptionSpeed(int speed);
    }
}
